package com.mjh.zhujianju.service.party.impl;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.livew.framework.base.model.FileEO;
import com.livew.framework.base.service.FileService;
import com.livew.framework.base.service.impl.BaseServiceImpl;
import com.livew.framework.enums.EStatus;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.page.PagedBeanUtil;
import com.livew.framework.page.PagedResult;
import com.livew.framework.utils.XTCurrentUser;
import com.livew.framework.utils.XTEntityUtils;
import com.livew.framework.utils.XTListUtils;
import com.mjh.zhujianju.dao.party.BuildingClassMapper;
import com.mjh.zhujianju.enums.BuildClassEnum;
import com.mjh.zhujianju.enums.BusinessEnum;
import com.mjh.zhujianju.model.agency.PolicyEO;
import com.mjh.zhujianju.model.base.ContentEO;
import com.mjh.zhujianju.model.party.BuildingClassDetailEO;
import com.mjh.zhujianju.model.party.BuildingClassEO;
import com.mjh.zhujianju.model.party.BuildingClassUsersDetailsEO;
import com.mjh.zhujianju.model.party.BuildingClassUsersEO;
import com.mjh.zhujianju.service.base.CommentService;
import com.mjh.zhujianju.service.base.ContentService;
import com.mjh.zhujianju.service.base.HitsService;
import com.mjh.zhujianju.service.party.BuildingClassDetailService;
import com.mjh.zhujianju.service.party.BuildingClassService;
import com.mjh.zhujianju.service.party.BuildingClassUsersDeatilsService;
import com.mjh.zhujianju.service.party.BuildingClassUsersService;
import com.mjh.zhujianju.util.FileUrlAdapter;
import com.mjh.zhujianju.vo.party.BuildingClassDetailVO;
import com.mjh.zhujianju.vo.party.BuildingClassVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liuyang
 * @Description: 课时
 * @date 2018/8/15 21:06
 */
@Service
public class BuildingClassServiceImpl extends BaseServiceImpl<BuildingClassEO> implements BuildingClassService {

    @Autowired
    private BuildingClassMapper buildingClassMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private BuildingClassDetailService buildingClassDetailService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private HitsService hitsService;

    @Autowired
    private BuildingClassUsersService buildingClassUsersService;

    @Autowired
    private BuildingClassUsersDeatilsService buildingClassUsersDeatilsService;


    public BuildingClassServiceImpl(BuildingClassMapper buildingClassMapper) {
        super(buildingClassMapper);
    }

    @Override
    public List<BuildingClassVO> queryBuildingClassForIndex() {
        List<BuildingClassVO> list = buildingClassMapper.queryBuildingClassForIndex();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }

        List<Long> ids = list.stream().map(buildingClassVO -> buildingClassVO.getId()).distinct().collect(Collectors.toList());

        //组装图片
        queryFileList(list, ids);
        return list;
    }

    @Override
    public List<BuildingClassVO> queryBuildingClassList(String type) {

        List<BuildingClassVO> list = buildingClassMapper.queryBuildingClassList(type);

        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<Long> ids = list.stream().map(buildingClassVO -> buildingClassVO.getId()).distinct().collect(Collectors.toList());

        //组装图片
        queryFileList(list, ids);

        //统计
        List<BuildingClassDetailVO> buildingClassDetailVOList = buildingClassDetailService.queryBuildingClassDetailTotal(ids);
        if (!CollectionUtils.isEmpty(buildingClassDetailVOList)) {
            for (BuildingClassVO buildingClass : list) {
                for (BuildingClassDetailVO buildingClassDetail : buildingClassDetailVOList) {
                    if (buildingClass.getId().equals(buildingClassDetail.getClassId())) {
                        buildingClass.setTotalClassHour(buildingClassDetail.getTotalClassHour());
                        continue;
                    }
                }
            }
        }
        return list;
    }

    @Override
    public BuildingClassVO queryBuildingClassInfo(Long id,Long userId) {

        //详情
        BuildingClassEO buildingClassEO = buildingClassMapper.selectByPrimaryKey(id);
        if (buildingClassEO == null) {
            return null;
        }

        BuildingClassVO buildingClassVO = new BuildingClassVO();
        BeanUtils.copyProperties(buildingClassEO, buildingClassVO);

        //课件列表
        List<BuildingClassDetailVO> buildingClassDetailEOList = buildingClassDetailService.queryBuildingClassDetailByClassId(buildingClassEO.getId());
        if (!CollectionUtils.isEmpty(buildingClassDetailEOList)) {
            buildingClassVO.setBuildingClassDetailList(buildingClassDetailEOList);
            buildingClassVO.setTotalClassHour(buildingClassDetailEOList.size());
        }

        String type = BusinessEnum.TYPE_CLASS.getCode();

        //课程详情
        ContentEO contentEO = contentService.queryContentByTypeAndId(type, buildingClassVO.getId());
        if (contentEO != null) {
            buildingClassVO.setContent(contentEO.getContent());
        }

        //图片
        List<Long> fileIds = fileService.getFileByCaseId(buildingClassVO.getId(), BuildingClassEO.class.getName(), null);
        if (CollectionUtils.isEmpty(fileIds)) {
            buildingClassVO.setFileAction(FileUrlAdapter.assemblyAction(fileIds.get(0)));
        }

        Integer totalClassHour = buildingClassDetailService.queryBuildingClassDetailTotalByClassId(id);
        buildingClassVO.setTotalClassHour(totalClassHour);

        buildingClassVO.setIsPlay("true");

        //查询当前是否加入过学习计划
        if (null != userId){
            List<BuildingClassUsersEO> classUsersEOS =  buildingClassUsersService.queryBuildingClassUsersEOByUserIdAndClassId(userId,id);
            if (CollectionUtils.isEmpty(classUsersEOS)){
                buildingClassVO.setIsPlay("false");
            }
        }
        return buildingClassVO;
    }

    @Override
    public void saveInfo(BuildingClassVO buildingClassVO) throws XTBusinessException {
        BuildingClassEO buildingClassEO = new BuildingClassEO();
        BeanUtils.copyProperties(buildingClassVO, buildingClassEO);
        if (StringUtils.isEmpty(buildingClassEO.getId())) {
            this.save(buildingClassEO);
            if (!XTListUtils.isEmpty(buildingClassVO.getFiles())) {
                fileService.updateList(buildingClassVO.getFiles(), buildingClassEO.getId(), BuildingClassEO.class.getName());
            }
            if (buildingClassVO.getBasicFunction() != null) {
                contentService.saveOrUpdate(BusinessEnum.TYPE_CLASS.getCode(), buildingClassEO.getId(), buildingClassVO.getBasicFunction());
            }
        } else {
            this.updateByPrimaryKey(buildingClassEO);
            if (!StringUtils.isEmpty(buildingClassVO.getFiles())) {
                fileService.updateList(buildingClassVO.getFiles(), buildingClassEO.getId(), BuildingClassEO.class.getName());
            }

            // 更新内容
            contentService.saveOrUpdate(BusinessEnum.TYPE_CLASS.getCode(), buildingClassEO.getId(), buildingClassEO.getBasicFunction());
        }
    }


    private void queryFileList(List<BuildingClassVO> list, List<Long> ids) {
        List<FileEO> fileList = fileService.getFileByIds(ids, BuildingClassEO.class.getName(), null);
        if (CollectionUtils.isEmpty(fileList)) {
            return;
        }
        list.stream().forEach(buildingClassVO -> {
            fileList.stream().forEach(fileEO -> {
                if (buildingClassVO.getId().equals(fileEO.getCaseId())) {
                    buildingClassVO.setFileId(fileEO.getId());
                    buildingClassVO.setFileAction(FileUrlAdapter.assemblyAction(fileEO.getId()));
                }
            });
        });
    }

    @Override
    public PagedResult<BuildingClassVO> findBuildingClassPagination(BuildingClassEO buildingClassEO) {
        Integer pageNo = buildingClassEO.getPageNo() == null ? 1 : buildingClassEO.getPageNo();
        Integer pageSize = buildingClassEO.getPageSize() == null ? 15 : buildingClassEO.getPageSize();
        PageHelper.startPage(pageNo, pageSize);
        List<BuildingClassEO> list = buildingClassMapper.selectPagination(buildingClassEO);
        PagedResult<BuildingClassEO> page = PagedBeanUtil.toPagedResult(list);
        PagedResult<BuildingClassVO> result = new PagedResult<BuildingClassVO>();
        BeanUtils.copyProperties(page, result);
        if (!XTListUtils.isEmpty(list)) {
            List<Long> ids = XTEntityUtils.getIdList(list);
            List<BuildingClassVO> voList = new ArrayList<BuildingClassVO>();
            Map<Long, FileEO> files = fileService.getMapTopOne(ids, BuildingClassEO.class.getName(), null);
            Map<Long,Long> classHours = buildingClassDetailService.getMapTopOne(ids);
            for (BuildingClassEO buildingClassEO1 : list) {
                BuildingClassVO d = new BuildingClassVO();
                BeanUtils.copyProperties(buildingClassEO1, d);
                d.setType(BuildClassEnum.getName(d.getType()));
                voList.add(d);
                FileEO file = files.get(d.getId());
                if (file != null) {
                    d.getFiles().add(file.getId());
                }

                Long totalClassHour = classHours.get(d.getId());
                if(totalClassHour != null){
                    d.setTotalClassHour(totalClassHour.intValue());
                }else {
                    d.setTotalClassHour(0);
                }
            }
            result.setDataList(voList);
        }
        return result;
    }
    private String getContent(Long id) {
        ContentEO content = contentService.queryContentByTypeAndId(BusinessEnum.TYPE_CLASS.getCode(), id);
        if (content != null) {
            return content.getContent();
        }
        return null;
    }

    @Override
    public BuildingClassVO getInfo(Long id) throws XTBusinessException {
        BuildingClassEO buildingNewsEO = super.getByPrimaryKey(id);
        if (buildingNewsEO != null) {
            BuildingClassVO vo = new BuildingClassVO();
            BeanUtils.copyProperties(buildingNewsEO, vo);
            vo.setBasicFunction(getContent(id));
            List<FileEO> files = fileService.getFileById(id, BuildingClassEO.class.getName(), null);
            if(!XTListUtils.isEmpty(files)) {
                vo.setFiles(XTEntityUtils.getIdList(files));
            }
            vo.setFileEOList(files);
            return vo;
        }
        return null;
    }

    @Override
    public Map<String, List<BuildingClassVO>> queryPlayList(Long userId) {

        //查询用户学习计划的数据
        List<BuildingClassUsersEO> buildingClassUsersEOList = buildingClassUsersService.findBuildingClassUsersEOByUserId(userId);
        if (CollectionUtils.isEmpty(buildingClassUsersEOList)){
            return null;
        }

        List<Long> ids = buildingClassUsersEOList.stream().map(buildingClassUsersEO -> buildingClassUsersEO.getClassId()).distinct().collect(Collectors.toList());

        List<BuildingClassEO> buildingClassEOList = buildingClassMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(buildingClassEOList)){
            return null;
        }

        //赋值进度
        List<BuildingClassVO> list = Lists.newArrayList();
        BuildingClassVO vo;
        for (BuildingClassEO eo : buildingClassEOList){
            vo = new BuildingClassVO();
            BeanUtils.copyProperties(eo,vo);
            for (BuildingClassUsersEO buildingClassUsersEO : buildingClassUsersEOList){
                if (vo.getId().equals(buildingClassUsersEO.getClassId())){
                    vo.setSchedule(buildingClassUsersEO.getSchedule());
                    continue;
                }
            }
            list.add(vo);
        }

        //组装图片
        queryFileList(list, ids);

        //统计
        List<BuildingClassDetailVO> buildingClassDetailVOList = buildingClassDetailService.queryBuildingClassDetailTotal(ids);
        if (!CollectionUtils.isEmpty(buildingClassDetailVOList)) {
            for (BuildingClassVO buildingClass : list) {
                for (BuildingClassDetailVO buildingClassDetail : buildingClassDetailVOList) {
                    if (buildingClass.getId().equals(buildingClassDetail.getClassId())) {
                        buildingClass.setTotalClassHour(buildingClassDetail.getTotalClassHour());
                        continue;
                    }
                }
            }
        }

        //分类
        Map<String, List<BuildingClassVO>> map = Maps.newHashMap();
        List<BuildingClassVO> finish = Lists.newArrayList();
        List<BuildingClassVO> unfinished = Lists.newArrayList();
        for (BuildingClassVO buildingClassVO : list){
            if (buildingClassVO.getSchedule().equals(100)){
                finish.add(buildingClassVO);
            }else {
                unfinished.add(buildingClassVO);
            }
        }
        map.put("finish",finish);
        map.put("unfinished",unfinished);
        return map;
    }

    @Override
    public BuildingClassVO queryBuildingClassInfoPlay(Long userId,Long id) {



        //详情
        BuildingClassEO buildingClassEO = buildingClassMapper.selectByPrimaryKey(id);
        if (buildingClassEO == null) {
            return null;
        }

        BuildingClassVO buildingClassVO = new BuildingClassVO();
        BeanUtils.copyProperties(buildingClassEO, buildingClassVO);

        //课件列表
        List<BuildingClassDetailVO> buildingClassDetailEOList = buildingClassDetailService.queryBuildingClassDetailByClassId(buildingClassEO.getId());
        if (!CollectionUtils.isEmpty(buildingClassDetailEOList)) {
            buildingClassVO.setBuildingClassDetailList(buildingClassDetailEOList);
            buildingClassVO.setTotalClassHour(buildingClassDetailEOList.size());

            List<BuildingClassUsersEO> list = buildingClassUsersService.findBuildingClassUsersEOByUserId(userId,id);
            List<BuildingClassUsersDetailsEO>  buildingClassUsersDetailsEOList = buildingClassUsersDeatilsService.findBuildingClassUsersEOByUserId(list.get(0).getId());

            for (BuildingClassDetailVO vo : buildingClassDetailEOList){
                for (BuildingClassUsersDetailsEO eo : buildingClassUsersDetailsEOList){
                    if (vo.getId().equals(eo.getClassDetailId())){
                        vo.setSchedule(eo.getSchedule());
                        continue;
                    }
                }
            }
        }

        String type = BusinessEnum.TYPE_CLASS.getCode();

        //课程详情
        ContentEO contentEO = contentService.queryContentByTypeAndId(type, buildingClassVO.getId());
        if (contentEO != null) {
            buildingClassVO.setContent(contentEO.getContent());
        }

        //浏览量+1
        hitsService.updateNumber(type, id);

        //图片
        List<Long> fileIds = fileService.getFileByCaseId(buildingClassVO.getId(), BuildingClassEO.class.getName(), null);
        if (CollectionUtils.isEmpty(fileIds)) {
            buildingClassVO.setFileAction(FileUrlAdapter.assemblyAction(fileIds.get(0)));
        }

        //统计浏览量
        Long hitsTotal = hitsService.queryHitsTotal(type, id);
        buildingClassVO.setTotalHits(hitsTotal);
        return buildingClassVO;
    }
}
